﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Controls;
using MSPToolkit.Models;
using MSPToolkit.Utilities;

namespace MSPToolkitSampleApp.UtilitesSamples
{
    public partial class ImageGeneratorSample : PhoneApplicationPage
    {
        Random rand = new Random();

        public ImageGeneratorSample()
        {
            InitializeComponent();
        }

        private void GenerateImageClick(object sender, RoutedEventArgs e)
        {
            var uris = new List<UriWithTransform>
            {
                new UriWithTransform{ Uri =new Uri("Images/2.png", UriKind.Relative), Height=300, Width=300, TranslateTransform=new TranslateTransform()},
                new UriWithTransform{ Uri =new Uri("Images/5.png", UriKind.Relative), Height=73, Width=100, TranslateTransform=new TranslateTransform() { X=GenerateRandInt(),Y=GenerateRandInt()}},
                new UriWithTransform{ Uri =new Uri("Images/6.png", UriKind.Relative), Height=33, Width=33, TranslateTransform=new TranslateTransform() { X=GenerateRandInt(),Y=GenerateRandInt()}},
                new UriWithTransform{ Uri =new Uri("Images/5.png", UriKind.Relative), Height=73, Width=100, TranslateTransform=new TranslateTransform() { X=GenerateRandInt(),Y=GenerateRandInt()}},
                new UriWithTransform{ Uri =new Uri("Images/6.png", UriKind.Relative), Height=33, Width=33, TranslateTransform=new TranslateTransform() { X=GenerateRandInt(),Y=GenerateRandInt()}},
            };
            var uri = ImageGenerator.GenerateImage(uris.Select(ImageGenerator.UriToImageWithTransform), "SampleImage.png", 300, 300);

            byte[] data;
            using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var isfs = isf.OpenFile(uri.LocalPath, FileMode.Open, FileAccess.Read))
                {
                    data = new byte[isfs.Length];
                    isfs.Read(data, 0, data.Length);
                    isfs.Close();
                }
            }

            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.SetSource(new MemoryStream(data));
            imageContainer.Source = bitmapImage;
        }

        private int GenerateRandInt()
        {
            return Convert.ToInt32(rand.NextDouble() * 250);
        }
    }
}